# -*- coding: utf-8 -*-
import jieba
from collections import Counter

# 读取temp.txt文件
with open('temp.txt', 'r', encoding='utf-8') as f:
    text = f.read()

# 使用jieba进行分词
words = jieba.lcut(text)

# 过滤词组，只保留长度大于1的词
filtered_words = [word for word in words if len(word) > 1]

# 统计词频
word_count = Counter(filtered_words)

# 获取高频词汇并按频率排序
most_common_words = word_count.most_common(30)  # 显示前30个高频词

# 将结果写入文件
with open('word_frequency_results.txt', 'w', encoding='utf-8') as f:
    f.write("《红楼梦》高频词汇列表（按词频从高到低）：\n")
    f.write("=" * 40 + "\n")
    for i, (word, count) in enumerate(most_common_words, 1):
        f.write(f"{i:2d}. {word:<12} {count:>4}次\n")

print("词频统计完成，结果已保存到word_frequency_results.txt文件中。")
print("\n《红楼梦》高频词汇列表（前10个）：")
print("=" * 30)
for i, (word, count) in enumerate(most_common_words[:10], 1):
    print(f"{i:2d}. {word:<12} {count:>4}次")